<?php

namespace App\Http\Middleware;

use App\Models\Permission;
use Closure;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission as SpatiePermission;

use Exception;

class ApiPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if($request->user()->hasAnyRole(['超级管理员'])){
            return $next($request);
        }
        $permission = Permission::where(['route' => $request->route()->getName(), 'guard_name' => 'api'])->first();
        if (!$permission) {
            throw new Exception('无此路由');
        }
        if ($request->user()->hasPermissionTo($permission->name, 'api')) {
            return $next($request);
        }
        // 权限不足
        throw new Exception('权限不足');
    }
}
